import { io } from '../utils/socket.io.esm.min.js'
import {
  getLocalMediaStream,
  getLocalScreenMediaStream,
  setVideoLocalStream,
  createPeerConnection,
  createVideoElement,
  setRemoteVideoStream
} from '../utils/index.js'

const roomInput = document.querySelector('#roomId')
const userIdInput = document.querySelector('#userId')
const startBtn = document.querySelector('.start')
const stopBtn = document.querySelector('.stop')
const videoBtn = document.querySelector('.video')
const screenBtn = document.querySelector('.screen')

const offerVideo = document.querySelector('#offerVideo')
let localStream = await getLocalMediaStream({
  audio: true,
  video: true
})

setVideoLocalStream(offerVideo, localStream)

let isRoomFull = false
let isInited = false
let roomId, userId, client, peer

let serverUrl = 'wss://' + window.location.host

startBtn.addEventListener('click', () => {
  if (isRoomFull) return alert('当前房间人数已满')
  roomId = roomInput.value
  userId = userIdInput.value

  if (!client) {
    client = new io(serverUrl, {
      reconnectDelayMat: 10000,
      transports: ['websocket'],
      query: {
        roomId,
        userId
      }
    })
  }

  client.on('connect', () => {
    console.log('连接成功')
  })

  client.on('disconnect', () => {
    console.log('连接断开')
  })

  client.on('error', e => {
    console.log('连接失败:', e)
  })

  client.on('people-count-msg', async count => {
    console.log('当前房间人数：', count)

    if (count === 1) {
      isInited = true
    }

    peer = createPeerConnection()
    localStream.getTracks().forEach(track => peer.addTrack(track, localStream))
    peer.onicecandidate = e => {
      if (e.candidate) {
        client.emit('candidate-msg', e.candidate)
      }
    }

    peer.ontrack = e => {
      const videoEle = createVideoElement(count)
      setRemoteVideoStream(videoEle, e.track)
    }

    if (!isInited) {
      let offerSDP = await peer.createOffer()
      await peer.setLocalDescription(offerSDP)
      client.emit('offer-sdp-msg', offerSDP)
    }
    isInited = true
  })

  client.on('room-full', () => {
    isRoomFull = true
    alert('当前房间人数已满')
  })

  client.on('offer-sdp-msg', async offerSDP => {
    peer.setRemoteDescription(offerSDP)
    let answerSDP = await peer.createAnswer()
    await peer.setLocalDescription(answerSDP)
    client.emit('answer-sdp-msg', answerSDP)
  })

  client.on('answer-sdp-msg', async answerSDP => {
    await peer.setRemoteDescription(answerSDP)
  })

  client.on('candidate-msg', async candidate => {
    await peer.addIceCandidate(candidate)
  })
})

let isStopAudio = false
let isStopVideo = false

stopBtn.addEventListener('click', () => {
  if (!peer) return
  isStopAudio = !isStopAudio
  isStopVideo = !isStopVideo

  peer.getSenders().forEach(sender => {
    if (sender.track.kind === 'audio') {
      sender.track.enabled = !isStopAudio
    }
    if (sender.track.kind === 'video') {
      sender.track.enabled = !isStopVideo
    }
  })
})

const replaceRemoteStream = stream => {
  if (!stream) return
  localStream = stream
  setVideoLocalStream(offerVideo, localStream)

  localStream.getTracks().forEach(track => {
    const videoSender = peer
      .getSenders()
      .find(sender => sender.track.kind === 'video')
    if (videoSender && track.kind === 'video') {
      videoSender.replaceTrack(track)
    }
  })
}

videoBtn.addEventListener('click', async () => {
  let newStream = await getLocalMediaStream({
    audio: true,
    video: true
  })
  replaceRemoteStream(newStream)
})

screenBtn.addEventListener('click', async () => {
  let newStream = await getLocalScreenMediaStream({
    cusor: 'always' | 'motion' | 'never',
    dispalySurface: 'application' | 'browser' | 'monitor' | 'window'
  })
  replaceRemoteStream(newStream)
})
